import javax.swing.*;
import java.awt.*;
import java.util.Random;

// Press Shift twice to open the Search Everywhere dialog and type `show whitespaces`,
// then press Enter. You can now see whitespace characters in your code.
public class game2048 extends JPanel{
    private static final int size=4;
    private final int[][] grid = new int[size][size];
    private final Random random = new Random();

    game2048(){
        spawntile();
        spawntile();
    }
    private void spawntile(){
        int x,y;
        do {
            x = random.nextInt(size);
            y = random.nextInt(size);
        }while (grid[x][y] != 0);
        grid[x][y]=random.nextInt(10)<5?2:4;
    }

    @Override
    protected void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setColor(Color.LIGHT_GRAY);
        g.fillRect(0,0,getWidth(),getHeight());
        for(int i=0;i<size;i++){
            for(int j=0;j<size;j++){
                //画小格子
                drawtile(g,grid[i][j],j*100,i*100);
            }
        }
    }

    private void drawtile(Graphics g,int value,int x,int y){
        int r = (int)(Math.log(value)/Math.log(2));
        g.setColor(value == 0 ? Color.GRAY : new Color(255-r*20,240,200));
        g.fillRect(x,y,100,100);
        g.setColor(Color.BLACK);
        g.drawRect(x,y,100,100);

        if(value !=0){
            String text =String.valueOf(value);
            FontMetrics fm = g.getFontMetrics();
            int w = fm.stringWidth(text);
            int h = fm.getHeight();
            int textx = x + (100-w)/2;
            int texty = y + (100-h)/2 + fm.getAscent();
            g.drawString(text,textx,texty);
        }
    }
    public static void main(String[] args) {
        JFrame frame = new JFrame("2048 Game");
        frame.setSize(420,460);
        game2048 game2048 = new game2048();
        frame.add(game2048);
        frame.setVisible(true);

    }
}